package com.iretailer.report.web.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iretailer.report.base.BaseAction;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.ReLangDict;
import com.iretailer.report.model.LangDict;
import com.iretailer.report.util.RMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Auther Bennie
 * @Date 2020/6/3 13:57
 * @Description
 */
@RestController
@RequestMapping("/business")
public class LangDictController extends BaseAction {


    @RequestMapping("/langDictList.action")
    public Map<String, Object> langDictList() {
        IPage<LangDict> page = new Page<>(1, Long.MAX_VALUE);
        QueryWrapper<LangDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", 1);
        IPage<LangDict> resultPage = langDictService.page(page, queryWrapper);
        PageResult<LangDict> result = new PageResult<>(resultPage.getTotal(), resultPage.getRecords());
        return RMap.ok(result);
    }

    @RequestMapping("/langDictPage.action")
    public Map<String, Object> langDictPage(
            @RequestBody ReLangDict reLangDict
    ) {
        PageResult<LangDict> result = langDictService.langDictPage(reLangDict);
        return RMap.ok(result);
    }


    @RequestMapping("/saveOrUpdateLangDict.action")
    public Map<String, Object> saveOrUpdateLangDict(@RequestBody LangDict langDict) {
        LocalDateTime now = LocalDateTime.now();
        if (StringUtils.isBlank(langDict.getId())) {
            if (langDictService.count(new QueryWrapper<LangDict>().lambda().eq(LangDict::getLangDictKey, langDict.getLangDictKey())) > 0) {
                return RMap.error(String.format("'%s' is already exists", langDict.getLangDictKey()));
            }
            langDict.setCreateTime(now);
        } else {
            langDict.setUpdateTime(now);
        }
        boolean result = langDictService.saveOrUpdate(langDict);
        return RMap.resultBoolean(result);
    }


    @RequestMapping("/delLangDict.action")
    public Map<String, Object> delLangDict(@RequestBody List<String> ids) {
        return RMap.resultBoolean(langDictService.removeByIds(ids));
    }
}
